<?php

namespace App\Http\Controllers\Admin;

use App\Http\Controllers\Api\ApiController;
use App\Http\Exports\RebateExport;
use App\Modules\Order\Models\Order;
use App\Modules\Rebate\Models\Rebate;
use App\Modules\Shop\Shop;
use App\Modules\User\Models\Admin;
use App\Modules\User\Models\User;
use Carbon\Carbon;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Auth;

class RebateController extends ApiController
{

    /**
     * 搜索门店
     */
    public function searchShops(Request $request){
        
        $this->checkAuth("merchant_staff_rebate", "rebate");
        $term = $request->input('term');
        $query = Shop::query();
        $query->where('status', 'open');
        if (!empty($term)) {
            $query->where('name', 'like', "%".$term."%");
        }

        if (isset($this->authUser->is_merchant_staff) && $this->authUser->is_merchant_staff == Admin::MERCHANT_AUTH) {
            $query->whereIn('id', json_decode($this->authUser->shop_id, true));
        }

        $re = $query
            ->get()
            ->pluck('name', 'id')
            ->all();

        $re[0] = '全部门店';
        return $re;
    }
    
    public function index(Request $request)
    {
        $this->checkAuth("merchant_staff_rebate", "rebate");
        $orderId = $request->input('order_id');
        $buyer = $request->input('buyer');
        $start = $request->input('start');
        $end = $request->input('end');
        $status = $request->input('status');
        $beneficiary = $request->input('beneficiary');
        $export = $request->input('export', 0);
        $merchant = $request->input('merchant');
        if ($this->authUser->is_merchant_staff == Admin::MERCHANT_AUTH) {
            $allShop = Shop::query()
                ->whereIn('id', json_decode($this->authUser->shop_id, true))
                ->get();
            $merchant = 1;
        } else {
            $allShop = Shop::query()->get();
        }


        $shopId = $request->input('shop_id', '');
        $shopName = $shopId ? Shop::query()->where('id', $shopId)->first('name')->name : '';
        $query = Rebate::query()
            ->join('orders', 'orders.id', '=', 'rebates.link_id')
            ->join('users', 'users.id', '=', 'orders.user_id')
            ->join('users as beneficiary', 'beneficiary.id', '=', 'rebates.user_id')
            ->select('rebates.*', 'orders.id as order_id', 'orders.name as buyer', 'orders.created_at as order_created_at', 'beneficiary.name as beneficiary_name', 'beneficiary.avatar as beneficiary_avatar')
            ->orderBy('orders.created_at', 'desc');
        if (!empty($status)) {
            switch ($status) {
                case 'init':
                    $query->where('rebates.status', Rebate::STATUS_INIT);
                    break;
                case 'issue':
                    $query->where('rebates.status', Rebate::STATUS_ISSUED);
                    break;
                case 'fail':
                    $query->where('rebates.status', Rebate::STATUS_FAIL);
                    break;
                case 'withdrawal':
                    $query->where('rebates.status', Rebate::STATUS_FINISH)
                        ->where('withdrawal_status', Rebate::WITHDRAWAL_STATUS_PENDING);
                    break;
                case 'finish':
                    $query->where('rebates.status', Rebate::STATUS_FINISH)
                        ->where('withdrawal_status', Rebate::WITHDRAWAL_STATUS_SUCCESS);
                    break;
            }
        }

        if (!empty($merchant)) {
            $query->whereIn('orders.shop_id', json_decode($this->authUser->shop_id, true));
        }

        if (!empty($shopId)) {
            $query->where('rebates.shop_id', $shopId);
        }
        if (!empty($end)) {
            $query->where('orders.created_at', '<', Carbon::parse($end)->addDay()->toDateString());
        }
        if (!empty($start)) {
            $query->where('orders.created_at', '>=', $start);
        }
        if (!empty($orderId)) {
            $query->where('orders.id', $orderId);
        }
        if (!empty($buyer)) {
            $query->where('orders.name', $buyer);
        }
        if (!empty($beneficiary)) {
            $query->where('beneficiary.name', 'like', '%' . $beneficiary . "%");
        }
        if ($export) {
            $data = $query->get()
                ->map(function ($item) {
                    return [
                        $item->order_id,
                        $item->beneficiary_name,
                        $item->buyer,
                        $item->order_created_at,
                        $item->money / 100,
                        $item->status == Rebate::STATUS_FINISH ? Rebate::$withdrawalStatusShow[$item->withdrawal_status] : Rebate::$statusShow[$item->status]
                    ];
                });
            return (new RebateExport("返利.xlsx", $data->all()))->downLoad();
        }
        $count = $query->count();
        $rebateMoney = $query->sum("money") / 100;
        $data = $query->paginate(20);

        $shopList = Shop::query()
                        ->whereIn('id', $data->pluck('shop_id')->all())
                        ->pluck('name', 'id')
                        ->all();

        return view('rebate.index', compact('data', 'rebateMoney', 'shopList', 'count', 'shopId', 'shopName','allShop', 'data', 'orders', 'orderId', 'buyer', 'start', 'end', 'status', 'beneficiary'));
    }

    public function delRebate(Request $request)
    {
        $this->checkAuth("merchant_staff_rebate_examine", "rebate-edit");
        $id = $request->input('id');
        $reject_reason = $request->input('reject_reason');
        Rebate::query()
            ->where('id', $id)
//            ->where('status', Rebate::STATUS_INIT)
            ->update([
                'status' => Rebate::STATUS_FAIL,
                'reject_reason' => $reject_reason
            ]);
        $rebate = Rebate::query()->where('id', $id)->first();

        /**
         *  临洮：提现审核不通过
         *  模板ID：q_Tusmt0Jzbg0XADplKd3avfqC9G3WWrmD9FUKL0iQA
         *  格式：
         * {{first.DATA}}
         * 提现金额：{{keyword1.DATA}}
         * 申请时间：{{keyword2.DATA}}
         * 审核状态：{{keyword3.DATA}}
         * 原因说明：{{keyword4.DATA}}
         * 时间：{{keyword5.DATA}}
         * {{remark.DATA}}
         */
        // $user = User::query()->find($rebate->id);
        // $sendData = [
        //     $user->openid,
        //     ($rebate->money / 100) . "元",
        //     date("Y年m月d日 H时i分s秒", strtotime($rebate->created_at)),
        //     "未通过",
        //     $reject_reason,
        //     date("Y年m月d日 H时i分s秒")
        // ];
        // sendMessage(28, $sendData);
        return redirect()->back();
    }

    /**
     * 通过审核  旧方法  暂时不用
     */
    public function passRebateOld($id)
    {
        $this->checkAuth("merchant_staff_rebate_examine", "rebate-edit");
        /** @var Rebate $rebate */
        $rebate = Rebate::query()
            ->where('id', $id)
            ->where('status', Rebate::STATUS_INIT)
            ->first();
        if (is_null($rebate)) {
            return redirect()->back()->withErrors('状态错误');
        }
        $rebate->update([
            'status' => Rebate::STATUS_ISSUED,
        ]);
        /** @var User $user */
        $user = User::query()
            ->where('id', $rebate->user_id)
            ->first();
        $account = $user->getAccount();
        $account->incrementMoney($rebate->money, 'system', "返利佣金");
        /**
         *  临洮：提现审核通过
         *  模板ID：q_Tusmt0Jzbg0XADplKd3avfqC9G3WWrmD9FUKL0iQA
         *  格式：
         * {{first.DATA}}
         * 提现金额：{{keyword1.DATA}}
         * 申请时间：{{keyword2.DATA}}
         * 审核状态：{{keyword3.DATA}}
         * 原因说明：{{keyword4.DATA}}
         * 时间：{{keyword5.DATA}}
         * {{remark.DATA}}
         */
        // $sendData = [
        //     $user->openid,
        //     ($rebate->money / 100) . "元",
        //     date("Y年m月d日 H时i分s秒", strtotime($rebate->created_at)),
        //     "已通过",
        //     "无",
        //     date("Y年m月d日 H时i分s秒")
        // ];
        // sendMessage(29, $sendData);
        return redirect()->back();
    }

    /**
     * 通过审核  新方法
     */
    public function passRebate(Request $request)
    {
        $this->checkAuth("merchant_staff_rebate_examine", "rebate-edit");
        
        $rebate_id       = $request->input('rebate_id', '');
        $withdrawal_type = $request->input('withdrawal_type', '');
        $withdrawal_time = $request->input('withdrawal_time', '');//提现时间，即用户个人中心提现记录可以展示的时间

        if (empty($rebate_id)) return redirect()->back()->withErrors('参数错误！');
        if ($withdrawal_type == 1 && $withdrawal_time == '') return redirect()->back()->withErrors('请选择提现时间');

        $withdrawal_time = $withdrawal_type == 0 ? date('Y-m-d H:i:s') : $withdrawal_time;

        /** @var Rebate $rebate */
        $rebate = Rebate::query()
            ->where('id', $rebate_id)
            ->where('status', Rebate::STATUS_INIT)
            ->first();
        if (is_null($rebate)) {
            return redirect()->back()->withErrors('状态错误');
        }

        $rebate->update([
            'status' => Rebate::STATUS_ISSUED,
            'withdrawal_type' => $withdrawal_type,
            'withdrawal_time' => $withdrawal_time,
        ]);

        /** @var User $user */
        $user = User::query()
            ->where('id', $rebate->user_id)
            ->first();
        $account = $user->getAccount();
        $account->incrementMoney($rebate->money, 'system', "返利佣金");

        /**
         *  临洮：提现审核通过
         *  模板ID：q_Tusmt0Jzbg0XADplKd3avfqC9G3WWrmD9FUKL0iQA
         *  格式：
         * {{first.DATA}}
         * 提现金额：{{keyword1.DATA}}
         * 申请时间：{{keyword2.DATA}}
         * 审核状态：{{keyword3.DATA}}
         * 原因说明：{{keyword4.DATA}}
         * 时间：{{keyword5.DATA}}
         * {{remark.DATA}}
         */
        // $sendData = [
        //     $user->openid,
        //     ($rebate->money / 100) . "元",
        //     date("Y年m月d日 H时i分s秒", strtotime($rebate->created_at)),
        //     "已通过",
        //     "无",
        //     date("Y年m月d日 H时i分s秒")
        // ];
        // sendMessage(29, $sendData);
        
        return redirect()->back();
    }

    /**
     * 返利撤回
     */
    public function revoke($id)
    {
        $this->checkAuth("merchant_staff_rebate_revoke", "rebate-revoke");
        /** @var Rebate $rebate */
        $rebate = Rebate::query()
            ->where('id', $id)
            ->first();
        if (is_null($rebate)) {
            return redirect()->back()->withErrors('找不到相关记录');
        }

        $rebate_status = $rebate->status;
        if ($rebate_status == 'issued') {
            $user = User::query()
                ->where('id', $rebate->user_id)
                ->first();
            $account = $user->getAccount();
            $account->decreaseMoney($rebate->money, 'system', '撤回', '后台管理员撤回');
        }

        $rebate->update([
            'status' => Rebate::STATUS_INIT,
            'revoke_time' => date('Y-m-d H:i:s'),
            'revoke_admin_id' => Auth::user()->id,
            'withdrawal_time' => '2020-01-01 00:00:00',//返利撤销，修改时间。
            'withdrawal_type' => 0,
        ]);       

        /**
         *  临洮：提现审核通过
         *  模板ID：q_Tusmt0Jzbg0XADplKd3avfqC9G3WWrmD9FUKL0iQA
         *  格式：
         * {{first.DATA}}
         * 提现金额：{{keyword1.DATA}}
         * 申请时间：{{keyword2.DATA}}
         * 审核状态：{{keyword3.DATA}}
         * 原因说明：{{keyword4.DATA}}
         * 时间：{{keyword5.DATA}}
         * {{remark.DATA}}
         */
        // $sendData = [
        //     $user->openid,
        //     ($rebate->money / 100) . "元",
        //     date("Y年m月d日 H时i分s秒", strtotime($rebate->created_at)),
        //     "已通过",
        //     "无",
        //     date("Y年m月d日 H时i分s秒")
        // ];
        // sendMessage(29, $sendData);
        return redirect()->back();
    }

}
